<script setup lang="ts">
import { ref, watch, nextTick, computed, onMounted, onUnmounted } from 'vue'
import { useUserStore } from '@/store/modules/user'
import { storeToRefs } from 'pinia'
import { MessageStatus, type Model } from '@/model'

const userStore = useUserStore()
const { currentMessageList, lastMessage, currentModel, modelList } = storeToRefs(userStore)

defineOptions({
  name: 'InputArea'
})

// 输入框的值
const inputValue = ref('')
const textareaRef = ref<HTMLTextAreaElement | null>(null)
const maxLines = 4 // Maximum number of lines before scrolling

// 模型选择相关
const showModelSelector = ref(false)

const modelSelectorRef = ref<HTMLElement | null>(null)

// 切换模型选择框显示状态
const toggleModelSelector = () => {
  showModelSelector.value = !showModelSelector.value
}

// 选择模型
const selectModel = (model: Model) => {
  userStore.currentModel = model
  showModelSelector.value = false
}

// 处理点击外部区域关闭选择框
const handleClickOutside = (event: MouseEvent) => {
  if (
    showModelSelector.value &&
    modelSelectorRef.value &&
    !modelSelectorRef.value.contains(event.target as Node)
  ) {
    showModelSelector.value = false
  }
}

// 在组件挂载时添加事件监听器
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

// 在组件卸载时移除事件监听器
onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})

// 是否可以发送消息
const canISending = computed(() => {
  // 如果最后一条消息是打字中，则不能发送消息
  if (lastMessage.value?.status === MessageStatus.Typing) return false
  // 如果输入框为空，则不能发送消息
  if (!inputValue.value.trim()) return false
  return true
})

// 定义事件
const emit = defineEmits<{
  (e: 'send-message', text: string): void
}>()

// 发送消息
const handleSendMessage = () => {
  if (!canISending.value) {
    return
  }
  // 添加用户消息
  currentMessageList.value?.push({
    id: Date.now(),
    sender: 'user',
    content: inputValue.value,
    avatar: 'C',
    status: MessageStatus.TypingDone
  })
  // 添加机器人消息
  currentMessageList.value?.push({
    id: Date.now(),
    sender: 'bot',
    content: '你好，我是小明',
    avatar: 'B',
    status: MessageStatus.Typing
  })

  // 清空输入框
  inputValue.value = ''

  // 调整 Textarea 高度
  adjustTextareaHeight()
}

// 点击按钮处理
const handleButtonClick = () => {
  if (lastMessage.value?.status === MessageStatus.Typing) {
    // 如果最后一条消息是typing状态，点击后设为failed
    lastMessage.value.status = MessageStatus.Failed
  } else {
    // 否则执行正常的发送逻辑
    handleSendMessage()
  }
}

// 调整 Textarea 高度
const adjustTextareaHeight = () => {
  nextTick(() => {
    const textarea = textareaRef.value
    if (textarea) {
      // Reset height to auto to get the actual scrollHeight
      textarea.style.height = 'auto'
      const scrollHeight = textarea.scrollHeight

      // Calculate line height (approximate)
      const computedStyle = window.getComputedStyle(textarea)
      const lineHeight = parseFloat(computedStyle.lineHeight) || 20 // Default line height
      const paddingTop = parseFloat(computedStyle.paddingTop) || 0
      const paddingBottom = parseFloat(computedStyle.paddingBottom) || 0

      // Calculate max height based on maxLines
      const maxHeight = lineHeight * maxLines + paddingTop + paddingBottom

      if (scrollHeight > maxHeight) {
        textarea.style.height = `${maxHeight}px`
        textarea.style.overflowY = 'auto' // Show scrollbar
      } else {
        textarea.style.height = `${scrollHeight}px`
        textarea.style.overflowY = 'hidden' // Hide scrollbar
      }
    }
  })
}

// 键盘事件处理
const handleKeyDown = (e: KeyboardEvent) => {
  if (e.key === 'Enter' && !e.shiftKey) {
    e.preventDefault()
    handleButtonClick()
  }
}

// Watch input value changes to adjust height
watch(inputValue, () => {
  adjustTextareaHeight()
})

// Initial adjustment on mount
watch(
  textareaRef,
  newRef => {
    if (newRef) {
      adjustTextareaHeight() // Adjust on mount in case there's initial value
    }
  },
  { immediate: true }
)
</script>

<template>
  <div class="p-4 border-t border-gray-200">
    <div class="relative max-w-3xl mx-auto">
      <!-- Main container for textarea and button -->
      <div class="flex flex-col rounded-3xl p-4 pl-6 bg-#f5f5f6 transition-all duration-150">
        <textarea
          ref="textareaRef"
          v-model="inputValue"
          placeholder="输入一条信息... (Shift+Enter 换行)"
          class="mb-2 border-none outline-none bg-#f5f5f6 resize-none overflow-hidden text-sm leading-snug pr-1 mr-3"
          rows="1"
          style="height: auto"
          @input="adjustTextareaHeight"
          @keydown="handleKeyDown"
        ></textarea>

        <!-- Send button -->
        <div class="flex items-center justify-between w-full">
          <div
            class="flex items-center rounded-full px-2 py-1 translate-y-3 translate-x--2 hover:bg-gray-200 cursor-pointer relative"
            @click.stop="toggleModelSelector"
            ref="modelSelectorRef"
          >
            <span class="text-gray-800 text-xs mr-1">{{ currentModel.name }}</span>
            <i class="iconfont icon-ios-arrow-down text-gray-800"></i>

            <!-- 模型选择弹出框 -->
            <div
              v-if="showModelSelector"
              class="absolute bottom-full left-0 mb-2 bg-white bd-1 rounded-lg shadow-lg p-2 z-10 min-w-[220px]"
              @click.stop
            >
              <div
                v-for="model in modelList"
                :key="model.id"
                class="p-2 hover:bg-gray-100 rounded cursor-pointer text-sm flex flex-col gap-1"
                @click.stop="selectModel(model)"
              >
                <span
                  class="text-gray-800"
                  :class="{ '!text-blue-500': model.id == currentModel.id }"
                  >{{ model.name }}</span
                >
                <span class="text-gray-400 text-xs">{{ model.description }}</span>
              </div>
            </div>
          </div>
          <div
            class="w-8 h-8 mt-2 bg-gray-800 flex flex-col items-center justify-center rounded-full hover:bg-gray-600 cursor-pointer self-end transition-all duration-150"
            @click="handleButtonClick"
          >
            <i
              class="iconfont icon-ios-send text-white !text-lg"
              v-if="lastMessage?.status !== MessageStatus.Typing"
            ></i>
            <i
              class="iconfont icon-ios-square text-white !text-lg"
              v-if="lastMessage?.status === MessageStatus.Typing"
            ></i>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* Ensure textarea has a reasonable base style and respects line height */
textarea {
  line-height: 1.5; /* Adjust as needed for your font */
}
</style>
